package com.android.volley.http;

import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import com.dg.acb.utils.LogUtil;

public class StringEntity implements RequestEntity {

    private Map<String, String> mParams = new HashMap<String, String>();

    public void addParam(final String name, final String value) {
        mParams.put(name, value);
    }

    public void writeTo(OutputStream out) throws IOException {
        if (mParams.size() > 0) {
            out.write(encodeParameters(mParams, getContentEncoding()));
        }
    }

    /**
     * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
     */
    protected byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
        StringBuilder encodedParams = new StringBuilder();
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (LogUtil.DEBUG) {
                    LogUtil.d("post:" + entry.getKey() + "=>" + entry.getValue());
                }
                encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                encodedParams.append('=');
                encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
                encodedParams.append('&');
            }
            Log.e("login","encodedParams is "+encodedParams);
            return encodedParams.toString().getBytes(paramsEncoding);
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
        }
    }

    @Override
    public String getContentType() {
        return "application/x-www-form-urlencoded; charset=" + getContentEncoding();
    }

    @Override
    public String getContentEncoding() {
        return DEFAULT_PARAMS_ENCODING;
    }
}